package com.tsd.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.tsd.CommonMsgNameConstants;
import com.tsd.CommonParamNameConstants;
import com.tsd.core.cache.CacheOperatorApi;
import com.tsd.core.config.session.SpringSessionContext;
import com.tsd.core.constants.Constants;
import com.tsd.core.constants.JwtConstants;
import com.tsd.core.constants.VersionConstants;
import com.tsd.core.datasource.DataSourceContextHolder;
import com.tsd.core.jwt.AccessToken;
import com.tsd.core.jwt.JwtUtils;
import com.tsd.core.shiro.IShiroConst;
import com.tsd.core.shiro.config.ShiroAuthToken;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.utils.HttpUtil;
import com.tsd.core.vo.*;
import com.tsd.jwt.JwtRefreshUtil;
import com.tsd.system.SysConstants;
import com.tsd.system.dao.SysGroupMapper;
import com.tsd.system.dao.SysUserMapper;
import com.tsd.system.entity.*;
import com.tsd.system.service.*;
import com.tsd.system.utils.SysUtil;
import com.tsd.system.vo.GlobalSetting;
import com.tsd.system.vo.MyUserInfo;
import com.tsd.system.vo.VerifyCodeVo;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.tsd.system.SysConstants.MESSAGE_LOGIN_USING_FOR_OTHER_USER;
import static com.tsd.system.SysConstants.MESSAGE_LOGIN_USING_OLD_PHONE;

/**
 * 描述：SysUser 控制层
 *
 * @author Hillpool
 * @date 2019/03/12 12:20:51
 */
@Controller
@Scope("prototype")
@RequestMapping("/api/v2")
public class SysUserController extends SystemBaseController {
    private static final Logger logger = LoggerFactory.getLogger(SysUserController.class);


    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysGroupMapper sysGroupMapper;
    @Resource
    private SysLoginInfoService sysLoginInfoService;
    @Resource
    private VerifyCodeGenService verifyCodeGenService;
    @Resource
    private SysExtSysUserService sysExtSysUserService;
    @Resource
    private SysAccountSetService sysAccountSetService;
    @Resource
    private SystemSettingService systemSettingService;
    @Resource
    private CacheOperatorApi<AccessToken> tokenCacheOperatorApi;
    @Resource
    SysUserMapper sysUserMapper;

    @ApiOperation(value = "根据sid查询用户")
    @ResponseBody
    @RequestMapping(value = "/getSysUserBySid.action", method = RequestMethod.POST)
    public HttpResult<SysUser> getSysUserBySid() {
        HttpResult<SysUser> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            String sid = HlpUtils.getString(map, CommonParamNameConstants.SID);
            if (HlpUtils.isEmpty(sid)) {
                return HttpResult.fail(ResponseCodeCore.CORE_MISSING_PARAM.code(), ResponseCodeCore.CORE_MISSING_PARAM.desc() + CommonParamNameConstants.SID);
            }
            SysUser sysUser = sysUserService.queryBySid(sid);
            hr.setData(sysUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }


    @ApiOperation(value = "分页查询用户以Map方式返回")
    @ResponseBody
    @RequestMapping(value = "/getSysUserParamsById.action", method = RequestMethod.POST)
    public HttpResult<Map<String, Object>> getSysUserParamsById() {
        HttpResult<Map<String, Object>> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Long id = HlpUtils.getLong(map, "id");
            super.checkEmpty(id, "请提供参数id");
            Map<String, Object> sysUser = sysUserService.getSysUserParamsById(id);
            hr.setData(sysUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "保存用户信息")
    @ResponseBody
    @RequestMapping(value = "/saveSysUser.action", method = RequestMethod.POST)
    public HttpResult<Object> saveSysUser() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUser sysUser = this.getSysUser();
            Map<String, Object> map = super.getParams(request);
            String json = JSON.toJSONString(map);
            SysUserExt userExt = JSON.parseObject(json, SysUserExt.class);
            if (!userExt.needUpdatePerson()) {
                //如果没有提交确认更新信息，则判断是否有已绑定的账户
                SysUserExt otherUser = sysUserService.personHasBindOtherUser(userExt);
                if (otherUser != null) {
                    hr.setData(otherUser);
                    hr.setCode(ErrorCode.CODE_PROC_GROUP_PERSON_HAS_BIND_OTHER_USER);
                    return hr;
                }
            }
            String dataSource = DataSourceContextHolder.getDataSourceType();
            if (HlpUtils.isEmpty(userExt.getId())) {
                DataSourceContextHolder.setDataSourceType(null);
                int ucLimit = sysUserService.getAccountSetUcLimit(dataSource);
                DataSourceContextHolder.setDataSourceType(dataSource);
                //统计不含admin的用户数量，以防删除了admin账户的情况,2024-04-29,由于去掉了login_id=admin的，主账号的sid为admin，所以直接获取countValid进行比较
                int count = sysUserMapper.countValid();
                if (ucLimit != 0 && count >= ucLimit) {
                    return HttpResult.fail(ErrorCode.CODE_PROC_ERROR, CommonMsgNameConstants.MAX_USER_QTY);
                }
            }
            sysUserService.saveSysUser(userExt, sysUser);
            SysUser user = sysUserService.queryByLoginId(userExt.getLogin_id());
            user.setPassword(null);
            hr.setData(user);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "根据ids批量删除", notes = "根据ids批量删除")
    @ResponseBody
    @RequestMapping(value = "/batchDelSysUser.action", method = RequestMethod.POST)
    public HttpResult<String> batchDelSysUser() throws HlpException {
        HttpResult<String> hr = new HttpResult<>();
        SysUser opUser = super.getSysUser();
        try {
            Map<String, Object> map = super.getParams(request);
            Object obj = map.get("sids");
            super.checkEmpty(obj, "请提供参数sids");
            if (obj instanceof List) {
                List<String> sids = JSONArray.parseArray(JSON.toJSONString(obj), String.class);
                if (sids.size() == 0) {
                    throw new HlpException("请至少选择一项");
                }
                sysUserService.batchDeleteSysUser(sids, opUser);
                hr.setCode(ErrorCode.CODE_SUCCESS);
            } else {
                return HttpResult.fail(ErrorCode.CODE_PROC_ERROR, CommonMsgNameConstants.DATA_TYPE_NOT_ARRAY);
            }
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }


    @ApiOperation(value = "根据参数获取人员信息")
    @ResponseBody
    @RequestMapping(value = "/findSysUsersByParams.action", method = RequestMethod.POST)
    public HttpResult<List<SysUserExt>> findSysUsersByParams() {
        HttpResult<List<SysUserExt>> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = new HashMap<>();
            HlpUtils.copyIntegerValue(map, params, "dr", "dr", true, Constants.VALUE_NO);
            HlpUtils.copyIntegerValue(map, params, "state", "state", false);
            HlpUtils.copyStringValue(map, params, "dept_sid", "dept_sid", false, false);
            HlpUtils.copyStringValue(map, params, "group_sid", "group_sid", false, false);
            List<SysUserExt> list = sysUserService.findSysUsersByParams(params);
            hr.setData(list);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "分页查询SysUser")
    @ResponseBody
    @RequestMapping(value = "/findSysUsers.action", method = RequestMethod.POST)
    public HttpResult<List<SysUserExt>> findSysUsers() {
        HttpResult<List<SysUserExt>> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = new HashMap<>();
            HlpUtils.copyIntegerValue(map, params, "dr", "dr", false, 0);
            HlpUtils.copyStringValue(map, params, "group_sid", "group_sid", false, false);
            HlpUtils.copyStringValue(map, params, "search_value", "search_value", false, true);
            HlpUtils.copyStringValue(map, params, "contract_team_sid", "contract_team_sid", false, false);
            HlpUtils.copyStringValue(map, params, "role_sid", "role_sid", false, false);
            HlpUtils.copyStringValue(map, params, "role_type", "role_type", false, false);
            HlpUtils.copyStringValue(map, params, "role_name", "role_name", false, false);
            HlpUtils.copyStringValue(map, params, "name", "name", false, true);
            HlpUtils.copyStringValue(map, params, CommonParamNameConstants.LOGIN_ID, CommonParamNameConstants.LOGIN_ID, false, false);
            HlpUtils.copyStringValue(map, params, "group_name", "group_name", false, false);
            HlpUtils.copyStringValue(map, params, "dept_sid", "dept_sid", false, false);
            HlpUtils.copyStringValue(map, params, "resource_client", "resource_client", false, false);
            Integer userType = HlpUtils.getInteger(map, "user_type");
            if (!HlpUtils.isEmpty(userType) && userType != -1) {
                params.put("user_type", userType);
            }
            PageBean page = new PageBean(map);
            if (map.containsKey(Constants.KEY_NO_PAGE)) {
                page = null;
            }
            List<SysUserExt> list = sysUserService.findSysUsers(params, page);
            hr.setData(list);
            hr.setPage(page);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "分页查询SysUser及部门、职务、人员特性等")
    @ResponseBody
    @RequestMapping(value = "/findSysUserParams.action", method = RequestMethod.POST)
    public HttpResult<List<Map<String, Object>>> findSysUserParams() {
        HttpResult<List<Map<String, Object>>> hr = new HttpResult<>();
        try {
            SysUserExt sysUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = new HashMap<>();
            String group_sid = HlpUtils.getString(map, "group_sid");
            if (HlpUtils.isEmpty(group_sid)) {
                SysGroupExt sysGroup = sysGroupMapper.selectBySid(sysUser.getGroup_sid());
                if (sysGroup != null) {
                    params.put("full_code", sysGroup.getFull_code());
                }
            } else {
                params.put("group_sid", group_sid);
            }
            HlpUtils.copyStringValue(map, params, "dept_sid", "deptSid", false, false);
            HlpUtils.copyStringValue(map, params, "search_value", "search_value", false, true);
            HlpUtils.copyIntegerValue(map, params, "dr", "dr", false, 0);
            HlpUtils.copyIntegerValue(map, params, "role_type", "role_type", false, 0);
            Integer userType = HlpUtils.getInteger(map, "userType");
            if (!HlpUtils.isEmpty(userType) && userType != -1) {
                params.put("userType", userType);
            }
            PageBean page = new PageBean(map);
            List<Map<String, Object>> list = sysUserService.findSysUserParams(params, page);
            hr.setData(list);
            hr.setPage(page);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "获取验证码")
    @RequestMapping(value = "/getVerifyCode.action")
    public void getVerifyCode(HttpServletResponse response) {
        try {
            VerifyCodeVo verifyCode = verifyCodeGenService.generate(request);
            //设置响应头
            response.setHeader(HttpHeaders.PRAGMA, "no-cache");
            //设置响应头
            response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");
            //在代理服务器端防止缓冲
            response.setDateHeader(HttpHeaders.EXPIRES, 0);
            //支持跨域请求
            response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, request.getHeader("Origin"));
            //是否支持cookie跨域
            response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
            response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "VerifySession");
            response.setHeader("VerifySession", verifyCode.getSessionId());
            //设置响应内容类型
            response.setContentType("image/jpeg");
            response.getOutputStream().write(verifyCode.getImgBytes());
            response.getOutputStream().flush();
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(404);
        }
    }

    String TestNGTag = "HillpoolTestNG";

    @ApiOperation(value = "用户登录")
    @ResponseBody
    @RequestMapping(value = "/login.action", method = RequestMethod.POST)
    public HttpResult<Object> login() {
        HttpResult<Object> resp = new HttpResult<>();
        long startTime = System.currentTimeMillis();
        String loginId;
        Map<String, Object> map;
        try {
            map = super.getParams(request);
            String testng = HlpUtils.getString(map, "testng");
            String verifySessionId = HlpUtils.getString(map, "verifySessionId");
            if (!TestNGTag.equals(testng)) {
                String verifyCode = HlpUtils.getString(map, "verifyCode");
                super.checkEmpty(verifyCode, "缺少参数：verifyCode");
                boolean verify = verifyCodeGenService.verify(verifyCode, verifySessionId);
                if (!verify) {
                    return HttpResult.fail(ErrorCode.CODE_PARAM_ERROR, SysConstants.MESSAGE_VERIFY_CODE_ERROR);
                }
            }
            String account_set_sid = HttpUtil.getAccountSet(request);
            SysAccountSetExt accountSetExt = null;
            if (!HlpUtils.isEmpty(account_set_sid)) {
                if (!DataSourceContextHolder.DEFAULT_ACCOUNT_SET_SID.equals(account_set_sid)) {
                    DataSourceContextHolder.setDataSourceType(null);
                    HttpResult<SysAccountSetExt> result = sysAccountSetService.checkSysAccountSetValid(account_set_sid);
                    if (ErrorCode.CODE_SUCCESS != result.getCode()) {
                        return HttpResult.procError(result.getMessage());
                    }
                    accountSetExt = result.getData();
                    HlpUtils.throwHlpException(accountSetExt.getMode() == null || !accountSetExt.getMode().contains(Constants.MODE_TSD), CommonMsgNameConstants.ERROR_MSG_ACCOUNT_NOT_OPENED);
                }
                DataSourceContextHolder.setDataSourceType(account_set_sid.trim());
            } else {
                DataSourceContextHolder.setDataSourceType(null);
            }
            // SysUserExt user = sysUserService.loginUser(map);
            // 2022/07/15 集成shiro登录
            loginId = HlpUtils.getString(map, CommonParamNameConstants.LOGIN_ID);
            String password = HlpUtils.getString(map, CommonParamNameConstants.PASSWORD);
            super.checkEmpty(loginId, CommonMsgNameConstants.getEmptyMsg(CommonParamNameConstants.LOGIN_ID));
            super.checkEmpty(password, CommonMsgNameConstants.EMPTY_MSG_PASSWORD);
            Subject subject = SecurityUtils.getSubject();
            ShiroAuthToken authToken = new ShiroAuthToken(loginId, password, null, IShiroConst.REALM_NAME_SYS_USER, JwtConstants.DEVICE_TYPE_PC);
            authToken.setAccount_set_sid(account_set_sid);
            subject.login(authToken);
            SysUserExt userExt = (SysUserExt) subject.getPrincipal();
            userExt.setVer(accountSetExt == null ? VersionConstants.VERSION_VALUE_ULTIMATE : VersionConstants.getVersionValue(accountSetExt.getVersion()));
            userExt.setExpired_date(accountSetExt == null ? null : accountSetExt.getExpired_date());
            if (VersionConstants.VERSION_VALUE_FREE == userExt.getVer()) {
                if (!HlpUtils.isEqual(loginId, account_set_sid)) {
                    return HttpResult.fail(ErrorCode.CODE_NO_AUTH, ErrorCode.MSG_FREE_ACCOUNT_LOGIN);
                }
            }
            GlobalSetting setting = systemSettingService.getGlobalSetting();
            if (setting != null) {
                userExt.setUrl_after_logined(setting.getUrl_after_logined());
            }
            loginSuccess(userExt, startTime, map);
            Integer tokenExpiredSeconds = JwtUtils.getTokenExpiredSeconds();
            String key = SysUtil.getTokenCacheKey(account_set_sid, userExt);
            tokenCacheOperatorApi.put(key, userExt.getAccessToken(), tokenExpiredSeconds.longValue());
            if (!TestNGTag.equals(testng)) {
                SpringSessionContext.removeSession(verifySessionId);
            }
            resp.setCode(ErrorCode.CODE_SUCCESS);
            resp.setData(userExt);
        } catch (Exception e) {
            if (MESSAGE_LOGIN_USING_OLD_PHONE.equalsIgnoreCase(e.getMessage()) ||
                    MESSAGE_LOGIN_USING_FOR_OTHER_USER.equalsIgnoreCase(e.getMessage())) {
                resp.setCode(ErrorCode.CODE_LOGIN_OLD_PHONE);
                resp.setMessage(e.getMessage());
            } else if (SysConstants.MESSAGE_VERIFY_CODE_ERROR.equalsIgnoreCase(e.getMessage())) {
                resp.setCode(ErrorCode.CODE_LOGIN_VERIFY_CODE_ERROR);
                resp.setMessage(e.getMessage());
            } else {
                super.procException(resp, e);
            }
        }
        return resp;
    }


    @ApiOperation(value = "用户登出")
    @ResponseBody
    @RequestMapping(value = "/logout.action", method = RequestMethod.POST)
    public HttpResult<String> logout() {
        HttpResult<String> hr = new HttpResult<>();
        try {
            SysUser opUser = this.getSysUser();
            sysUserService.logout(opUser);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }
    public void loginSuccess(SysUserExt user, long startTime, Map<String, Object> map) throws Exception {
        //生成登录信息
        SysLoginInfo loginInfo = new SysLoginInfo();
        loginInfo.setUser_sid(user.getSid());
        sysLoginInfoService.saveSysLoginInfo(loginInfo, user);
        // TODO 需要调整2021-07-05 wudw
        //拼装accessToken
        JwtRefreshUtil.createSysUserToken(user);
    }

    @ApiOperation(value = "用户App登录")
    @ResponseBody
    @RequestMapping(value = "/loginApp.action", method = RequestMethod.POST)
    public HttpResult<Object> loginApp() {
        HttpResult<Object> resp = new HttpResult<>();
        long startTime = System.currentTimeMillis();
        Map<String, Object> map;
        try {
            map = super.getParams(request);
            String account_set_sid = HttpUtil.getAccountSet(request);
            if (!HlpUtils.isEmpty(account_set_sid)) {
                DataSourceContextHolder.setDataSourceType(null);
                HttpResult<SysAccountSetExt> result = sysAccountSetService.checkSysAccountSetValid(account_set_sid);
                if (ErrorCode.CODE_SUCCESS != result.getCode()) {
                    return HttpResult.procError(result.getMessage());
                }
                DataSourceContextHolder.setDataSourceType(account_set_sid.trim());
            } else {
                DataSourceContextHolder.setDataSourceType(null);
            }
            SysUserExt user = sysUserService.loginUser(map);
            //生成登录信息
            SysLoginInfo loginInfo = new SysLoginInfo();
            loginInfo.setUser_sid(user.getSid());
            sysLoginInfoService.saveSysLoginInfo(loginInfo, user);
            // TODO 需要调整2021-07-05 wudw
            //拼装accessToken
            JwtRefreshUtil.createSysUserToken(user);
            resp.setCode(ErrorCode.CODE_SUCCESS);
            resp.setData(user);
        } catch (Exception e) {
            if (MESSAGE_LOGIN_USING_OLD_PHONE.equalsIgnoreCase(e.getMessage()) ||
                    MESSAGE_LOGIN_USING_FOR_OTHER_USER.equalsIgnoreCase(e.getMessage())) {
                resp.setCode(ErrorCode.CODE_LOGIN_OLD_PHONE);
                resp.setMessage(e.getMessage());
            } else {
                super.procException(resp, e);
            }
        }
        return resp;
    }
//    @ApiOperation(value = "游客登录，用于扫码二维码查看部位信息")
//    @ResponseBody
//    @RequestMapping(value = "/loginGuest.action", method = RequestMethod.POST)
//    public HttpResult<SysUser> loginGuest() {
//        HttpResult<SysUser> resp = new HttpResult<SysUser>();
//        long startTime = System.currentTimeMillis();
//        try {
//            SysUserExt user = new SysUserExt();
//            user.setLogin_id("guest");
//            user.setName("游客");
//            String token = JwtHelper.createJWT(user);
//            JwtRefreshUtil.addCacheToken(token, user);
//            //返回accessToken
//            JwtRefreshUtil.createSysUserToken(user);
//            resp.setCode(ErrorCode.CODE_SUCCESS);
//            resp.setData(user);
//            writeLog(request, user.getSid(), user.getName(), startTime, ErrorCode.CODE_SUCCESS, new HashMap<>());
//        } catch (Exception e) {
//            super.procException(resp, e);
//        }
//        return resp;
//    }

    @ApiOperation(value = "刷新token")
    @ResponseBody
    @RequestMapping(value = "/refreshToken.action", method = RequestMethod.POST)
    public HttpResult<SysUser> refreshToken() {
        HttpResult<SysUser> hr = new HttpResult<>();
        try {
            SysUserExt opUser = this.getSysUser();
            if (opUser == null) {
                return HttpResult.fail(ResponseCodeCore.CORE_NO_LOGIN.code(), ResponseCodeCore.CORE_NO_LOGIN.desc());
            }
            //拼装accessToken
            JwtRefreshUtil.createSysUserToken(opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
            hr.setData(opUser);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "重置密码")
    @ResponseBody
    @RequestMapping(value = "/resetPwd.action", method = RequestMethod.POST)
    public HttpResult<SysUser> resetPwd() {
        HttpResult<SysUser> hr = new HttpResult<>();
        try {
            SysUser opUser = this.getSysUser();
            Map<String, Object> map = super.getParams(request);
            String userId = HlpUtils.getString(map, CommonParamNameConstants.SID);
            String password = HlpUtils.getString(map, "password");
            super.checkEmpty(userId, "缺少参数sid");
            super.checkEmpty(password, "缺少参数password");
            if (opUser == null) {
                return HttpResult.fail(ResponseCodeCore.CORE_NO_LOGIN.code(), ResponseCodeCore.CORE_NO_LOGIN.desc());
            }
            if (opUser.getSid().equals(userId)) {
                throw new HlpException("不能重置自己的密码");
            }
            sysUserService.resetPwd(userId, password);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "修改密码")
    @ResponseBody
    @RequestMapping(value = "/changePwd.action", method = RequestMethod.POST)
    public HttpResult<String> changePwd() {
        HttpResult<String> hr = new HttpResult<>();
        try {
            SysUser opUser = this.getSysUser();
            Map<String, Object> map = super.getParams(request);
            String sid = HlpUtils.getString(map, CommonParamNameConstants.SID);
            String password = HlpUtils.getString(map, "password");
            String newPassword = HlpUtils.getString(map, "newPassword");
            super.checkEmpty(sid, "缺少参数sid");
            super.checkEmpty(password, "缺少参数password");
            super.checkEmpty(newPassword, "缺少参数newPassword");
            HttpResult<String> shr = sysUserService.changePwd(opUser, sid, password, newPassword);
            if (shr == null) {
                hr.setCode(ErrorCode.CODE_SUCCESS);
            }else{
                return shr;
            }
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "根据登录账号查询用户")
    @ResponseBody
    @RequestMapping(value = "/queryUserByLoginId.action", method = RequestMethod.POST)
    public HttpResult<Object> queryUserByLoginId() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            String login_id = HlpUtils.getString(map, CommonParamNameConstants.LOGIN_ID);
            super.checkEmpty(login_id, "请提供参数login_id");
            SysUser sysUser = sysUserService.queryByLoginId(login_id);
            if (sysUser == null) {
                throw new HlpException("登录账户不存在");
            }
            sysUser.setPassword(null);
            hr.setData(sysUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "忘记密码时的重置密码")
    @ResponseBody
    @RequestMapping(value = "/resetPwd4Forget.action", method = RequestMethod.POST)
    public HttpResult<SysUser> resetPwd4Forget() {
        HttpResult<SysUser> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            String userId = HlpUtils.getString(map, CommonParamNameConstants.USER_ID);
            String password = HlpUtils.getString(map, "password");
            super.checkEmpty(userId, "缺少参数user_id");
            super.checkEmpty(password, "缺少参数password");
            sysUserService.resetPwd(userId, password);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "从Token得到用户信息")
    @ResponseBody
    @RequestMapping(value = "/getUserInfoFromToken.action", method = RequestMethod.POST)
    public HttpResult<Object> getUserInfoFromToken() {
        HttpResult<Object> resp = new HttpResult<>();
        try {
            SysUserExt user = super.getSysUser();
            user = sysUserService.queryBySid(user.getSid());
            user.setPassword(null);
            JwtRefreshUtil.createSysUserToken(user);
            resp.setCode(ErrorCode.CODE_SUCCESS);
            resp.setData(user);
        } catch (Exception e) {
            super.procException(resp, e);
        }
        return resp;
    }


    @ApiOperation(value = "根据group_sid查询SysUser")
    @ResponseBody
    @RequestMapping(value = "/findSysUsersByGroupSid.action", method = RequestMethod.POST)
    public HttpResult<List<SysUserExt>> findSysUsersByGroupSid() {
        HttpResult<List<SysUserExt>> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            String group_sid = HlpUtils.getString(map, "group_sid");
            super.checkEmpty(group_sid, "参数group_sid不能为空");
            List<SysUserExt> list = sysUserService.findUserByOrgSid(group_sid);
            hr.setData(list);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "获取未绑定的用户")
    @ResponseBody
    @RequestMapping(value = "/findUnBindSysUser.action", method = RequestMethod.POST)
    public HttpResult<List<SysUserExt>> findUnBindSysUser() {
        HttpResult<List<SysUserExt>> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = new HashMap<>();
            HlpUtils.copyStringValue(map, params, "search_value", "search_value", false, true);
            HlpUtils.copyIntegerValue(map, params, "dr", "dr", false, 0);
            HlpUtils.copyStringValue(map, params, "user_sid", "user_sid", false, false);
            List<SysUserExt> list = sysUserService.findUnBindSysUser(params);
            hr.setData(list);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "修改个人信息")
    @ResponseBody
    @RequestMapping(value = "/saveMyUserInfo.action", method = RequestMethod.POST)
    public HttpResult<Object> saveMyUserInfo() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUser opUser = this.getSysUser();
            Map<String, Object> map = super.getParams(request);
            MyUserInfo myUserInfo = JSON.parseObject(JSON.toJSONString(map), MyUserInfo.class);
            sysUserService.saveMyUserInfo(myUserInfo, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "获取当前用户信息")
    @ResponseBody
    @RequestMapping(value = "/getMyUserInfo.action", method = RequestMethod.POST)
    public HttpResult<MyUserInfo> getMyUserInfo() {
        HttpResult<MyUserInfo> hr = new HttpResult<>();
        try {
            SysUser opUser = this.getSysUser();
            SysUserExt sysUser = sysUserService.queryBySid(opUser.getSid());
            MyUserInfo myInfo = JSON.parseObject(JSON.toJSONString(sysUser), MyUserInfo.class);
            List<SysExtSysUserExt> bindList = sysExtSysUserService.findSysExtSysUsersByUserSid(opUser.getSid());
            myInfo.setBindList(bindList);
            hr.setData(myInfo);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * log4j漏洞代码执行漏洞
     * 将log4j升级到官方最新版本（>= log4j-2.15.0版本），并且修改log4j的配置禁用日志的lookup功能具体方法如下：
     * 1、将log4j升级到官方最新版本（>= log4j-2.15.0版本）。
     * 2、关闭log4j的lookup功能：
     * a. 在 JVM 启动参数中加上 -Dlog4j2.formatMsgNoLookups=true 和 -Dlog4j=formatMsgNoLookups=true .
     * b. 在应用程序的classpath中的log4j2.component.properties配置文件（如果没有文件，则手工新建）中添加如下两行内容：
     * log4j2.formatMsgNoLookups=True
     * log4j.formatMsgNoLookups=True
     *
     * @return
     */
    @ApiOperation(value = "测试log4j漏洞")
    @ResponseBody
    @RequestMapping(value = "/testLog4jBug.action", method = RequestMethod.GET)
    public HttpResult<Object> testLog4jBug() {
        HttpResult<Object> hr = new HttpResult<>();
        String error = "${java:version}";
        logger.error("=====危险打印==,{}", error);
        return hr;
    }


    @ApiOperation(value = "分页查询SysUser基本信息")
    @ResponseBody
    @RequestMapping(value = "/findSysUserBaseInfos.action", method = RequestMethod.POST)
    public HttpResult<List<SysUserExt>> findSysUserBaseInfos() {
        HttpResult<List<SysUserExt>> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = new HashMap<>();
            HlpUtils.copyIntegerValue(map, params, "dr", "dr", false, 0);
            HlpUtils.copyStringValue(map, params, "group_sid", "group_sid", false, false);
            HlpUtils.copyStringValue(map, params, "search_value", "search_value", false, true);
            HlpUtils.copyStringValue(map, params, "contract_team_sid", "contract_team_sid", false, false);
            HlpUtils.copyStringValue(map, params, "role_sid", "role_sid", false, false);
            HlpUtils.copyStringValue(map, params, "role_type", "role_type", false, false);
            HlpUtils.copyStringValue(map, params, "role_name", "role_name", false, false);
            HlpUtils.copyStringValue(map, params, "name", "name", false, true);
            HlpUtils.copyStringValue(map, params, CommonParamNameConstants.LOGIN_ID, CommonParamNameConstants.LOGIN_ID, false, false);
            HlpUtils.copyStringValue(map, params, "group_name", "group_name", false, false);
            HlpUtils.copyStringValue(map, params, "dept_sid", "dept_sid", false, false);
            HlpUtils.copyStringValue(map, params, "resource_client", "resource_client", false, false);
            Integer userType = HlpUtils.getInteger(map, "user_type");
            if (!HlpUtils.isEmpty(userType) && userType != -1) {
                params.put("user_type", userType);
            }
            PageBean page = new PageBean(map);
            if (map.containsKey(Constants.KEY_NO_PAGE)) {
                page = null;
            }
            List<SysUserExt> list = sysUserService.findSysUserBaseInfos(params, page);
            hr.setData(list);
            hr.setPage(page);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }
}
